package com.test5.liang.config;

import com.test5.liang.login.LoginSuccessHandler;
import com.test5.liang.login.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsServiceImpl customUserService(){ //注册UserDetailsService 的bean
        return new UserDetailsServiceImpl();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/resources/**","/static/all/**","/", "/home","/test","/signUp","/checksignUp").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .successHandler(new LoginSuccessHandler())
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .and()
                //配置记住我
                .rememberMe().rememberMeParameter("remember");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/all/**").antMatchers("/templates/**");
    }


    @Override
    protected UserDetailsService userDetailsService() {
        return customUserService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //AuthenticationManager使用我们的 Service来获取用户信息，Service可以自己写，其实就是简单的读取数据库的操作
        auth.userDetailsService(customUserService()); // （6）
    }


}
